<template>
  <el-dialog
    v-model="dialogVisibleMaterial"
    title="选择合同内材料"
    width="70%"
    overflow
    @close="handleClose"
  >
    <template #footer>
      <el-form
        :model="searchForm"
        label-width="auto"
        :inline="true"
        size="small"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="材料编码">
              <el-input
                v-model="searchForm.materialCode"
                placeholder="请输入 材料编码"
                class="!w-[200px]"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="材料名称">
              <el-input
                v-model="searchForm.materialName"
                placeholder="请输入 材料名称"
                class="!w-[200px]"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="规格">
              <el-input
                v-model="searchForm.materialTexture"
                placeholder="请输入 规格"
                class="!w-[200px]"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: right">
            <el-button
              color="#1E3485"
              @click="
                tablePage.currentPage = 1;
                getlist();
              "
              >搜索</el-button
            >
            <el-button type="default" @click="clearAllFields">清空</el-button>
          </el-col>
        </el-row>
      </el-form>
      <vxe-table
        ref="tableRef"
        border
        min-height="300"
        :data="TableData"
        :column-config="{ resizable: true }"
        :row-config="{ isHover: true }"
        header-align="center"
        show-footer
        size="mini"
        :checkbox-config="checkboxConfig"
        @checkbox-all="selectAllChangeEvent"
        @checkbox-change="selectChangeEvent"
      >
        <vxe-column type="checkbox" width="40" />
        <vxe-column type="seq" title="序号" width="60" />
        <vxe-column field="materialCode" title="材料编码" width="150" />
        <vxe-column field="materialName" title="材料名称" width="120" />
        <vxe-column
          field="materialSpecs"
          title="规格"
          width="200"
          show-overflow
        />
        <vxe-column field="materialModel" title="型号" width="100" />
        <vxe-column field="materialUnit" title="单位" width="100" />
        <vxe-column field="materialBrand" title="品牌" width="100" />
        <vxe-column field="materialNum" title="数量" width="100" />
        <vxe-column
          field="excludingTaxUnitPrice"
          title="不含税单价(元)"
          width="120"
        />
        <vxe-column
          field="includingTaxUnitPrice"
          title="含税单价(元)"
          width="120"
        />
        <vxe-column
          field="includingTaxTotalPrice"
          title="含税总价(元)"
          width="120"
        />
        <vxe-column
          field="materialMark"
          title="备注"
          width="100"
          show-overflow
        />
      </vxe-table>
      <vxe-pager
        v-model:current-page="tablePage.currentPage"
        v-model:page-size="tablePage.pageSize"
        :layouts="[
          'Sizes',
          'PrevJump',
          'PrevPage',
          'Number',
          'NextPage',
          'NextJump',
          'FullJump',
          'Total'
        ]"
        :total="tablePage.total"
        size="small"
        @page-change="handlePageChange"
      />
      <div class="dialog-footer">
        <el-button type="primary" color="#1E3485" @click="go()">
          确认
        </el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, watch, onMounted } from "vue";
import { VxeTablePropTypes } from "vxe-table";
import { VxeTableInstance, VxePagerEvents, VxeTableEvents } from "vxe-table";
import { ElMessage } from "element-plus";
import { getmaterialselectlist } from "@/api/ERP_OrderManage";

const emit = defineEmits(["close", "confirm"]);
function handleClose() {
  clearAllFields();
  emit("close", false);
}
const searchForm = ref({
  contractId: "",
  materialCode: "",
  materialTexture: "",
  materialName: ""
});

//获取材料列表
const getlist = (query?: string) => {
  let params: any = {};
  params.pageIndex = tablePage.currentPage;
  params.pageSize = tablePage.pageSize;
  params.contractId = props.contractId;
  params.materialCode = searchForm.value.materialCode;
  params.materialSpecs = searchForm.value.materialTexture;
  params.materialName = searchForm.value.materialName;
  if (props.materiaTableData.length > 0) {
    params.contractMaterialIdList = contractMaterialIdList.value;
  }
  getmaterialselectlist(params).then((response: any) => {
    // if (props.materiaTableData.length > 0) {
    //   let bindIdMap = new Map(
    //     props.materiaTableData.map((item: any) => [item.materialBindId, item])
    //   );
    //   let filteredRecords = response.data.records.filter(record => {
    //     return !bindIdMap.has(record.id);
    //   });
    //   TableData.value = filteredRecords;
    // } else {
    // }
    TableData.value = response.data.records;
    tablePage.total = response.data.totalElements;
  });
  if (query) {
    setTimeout(() => {
      getmaterialselectlist;
    }, 1500);
  }
};

const TableData = ref([]);
// 弹窗关闭/打开事件
const props = defineProps({
  visible: Boolean,
  contractId: String,
  materiaTableData: Array
});

const dialogVisibleMaterial = ref(false);
// 表格分页配置
const tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
});
const contractMaterialIdList = ref([]);
watch(
  () => props.visible,
  val => {
    dialogVisibleMaterial.value = val;
    if (props.contractId != "") {
      if (props.materiaTableData.length > 0) {
        contractMaterialIdList.value = [];
        for (let i in props.materiaTableData) {
          contractMaterialIdList.value.push(
            props.materiaTableData[i].contractMaterialId
          );
        }
      }
      getlist();
    }
  },
  { immediate: true }
);
const tableRef = ref();
// 表格分页事件
const handlePageChange: VxePagerEvents.PageChange = ({
  currentPage,
  pageSize
}) => {
  tablePage.currentPage = currentPage;
  tablePage.pageSize = pageSize;
  getlist();
};
const selectRow = ref([]);
const selectAllChangeEvent: VxeTableEvents.CheckboxAll = ({ checked }) => {
  const $table = tableRef.value;
  if ($table) {
    selectRow.value = $table.getCheckboxRecords();
  }
};
const selectChangeEvent: VxeTableEvents.CheckboxChange = ({ checked }) => {
  const $table = tableRef.value;
  if ($table) {
    selectRow.value = $table.getCheckboxRecords();
  }
};
function go() {
  if (selectRow.value.length == 0) {
    ElMessage.warning("请选择要添加的行");
    return;
  }
  emit("confirm", selectRow);
  dialogVisibleMaterial.value = false;
  selectRow.value = [];
}
// 清空按钮点击事件
const clearAllFields = () => {
  searchForm.value.materialCode = "";
  searchForm.value.materialTexture = "";
  searchForm.value.materialName = "";
};

const checkboxConfig = reactive<VxeTablePropTypes.CheckboxConfig>({});
</script>
<style lang="scss" scoped>
.dialog-footer {
  margin-top: 20px;
}
</style>
